package com.game.sdk.view;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.text.TextUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.game.sdk.YTAppService;
import com.game.sdk.db.impl.UserLoginInfodao;
import com.game.sdk.domain.LogincallBack;
import com.game.sdk.domain.OnLoginListener;
import com.game.sdk.domain.ResultCode;
import com.game.sdk.domain.UserInfo;
import com.game.sdk.floatwindow.Constant;
import com.game.sdk.floatwindow.FloatWebActivity;
import com.game.sdk.init.NetCallBack;
import com.game.sdk.login.LoginUtils;
import com.game.sdk.popwindow.SelectPopupWindow;
import com.game.sdk.ui.LoginActivity.onRegisterBack;
import com.game.sdk.util.Constants;
import com.game.sdk.util.DialogUtil;
import com.game.sdk.util.GetDataImpl;
import com.game.sdk.util.JsonUtil;
import com.game.sdk.util.Logger;
import com.game.sdk.util.MResource;
import com.game.sdk.util.Util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class OneRegisterUser extends BaseView {
	public static Activity acontext;
	private static OnLoginListener loginListener;// 登录回调监听
	private boolean isoneregister;
	private EditText et_username, et_pwd;
	private String uname = "";
	private SharedPreferences sp;
	private UserInfo userinfo;
	public static boolean isSelfRegister = false; // 用来标记是否是自定义注册 调整到登录页面的
	public static String username, pwd;
	private Button btn_game_in;
	private RelativeLayout rl_oneregister_back_login;
	private boolean isPortrait;// 是否是竖版

	/**
	 * 构造方法 用来示例view对象
	 * 
	 * @param ctx
	 */
	public OneRegisterUser(Activity ctx, OnLoginListener logininlist,
			boolean isoneregister) {
		this.isoneregister = isoneregister;
		acontext = ctx;
		inflater = (LayoutInflater) ctx
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		loginListener = logininlist;
		isPortrait = (acontext.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT);

		if (isoneregister) {
			if (isPortrait) {
				content_view = inflater.inflate(MResource.getIdByName(ctx,
						Constants.Resouce.LAYOUT, "sdk_oneregister"), null);
			} else {
				content_view = inflater.inflate(MResource.getIdByName(ctx,
						Constants.Resouce.LAYOUT, "sdk_oneregister_landscape"),
						null);
			}
		} else {
			if (isPortrait) {
				content_view = inflater.inflate(MResource.getIdByName(ctx,
						Constants.Resouce.LAYOUT, "sdk_user_register"), null);
			} else {
				content_view = inflater.inflate(MResource
						.getIdByName(ctx, Constants.Resouce.LAYOUT,
								"sdk_user_register_landscape"), null);
			}

		}
		initData();
		rl_oneregister_back_login = (RelativeLayout) content_view
				.findViewById(MResource.getIdByName(ctx, Constants.Resouce.ID,
						"rl_oneregister_back_login"));
		btn_game_in = (Button) content_view.findViewById(MResource.getIdByName(
				ctx, Constants.Resouce.ID, "btn_game_in"));
		et_username = (EditText) content_view.findViewById(MResource
				.getIdByName(ctx, Constants.Resouce.ID, "et_username"));
		et_pwd = (EditText) content_view.findViewById(MResource.getIdByName(
				ctx, Constants.Resouce.ID, "et_pwd"));
		btn_game_in.setOnClickListener(this);
		et_username.setText(uname);
		sp = acontext.getSharedPreferences(Constants.CONFIG,
				Context.MODE_PRIVATE);

	}

	/**
	 * 初始化相关数据
	 */
	private void initData() {
		userinfo = new UserInfo();
		TelephonyManager tm = (TelephonyManager) acontext
				.getSystemService(Context.TELEPHONY_SERVICE);
		userinfo.imeil = tm.getDeviceId();
		userinfo.deviceinfo = tm.getLine1Number() + "||android"
				+ Build.VERSION.RELEASE;

		userinfo.agent = YTAppService.agentid;
	}

	public void setOnClick(OnClickListener onclick) {
		rl_oneregister_back_login.setOnClickListener(onclick);

	}

	/**
	 * 一键注册
	 */
	public void OneKeyRegister(onRegisterBack onregister) {
		if (null == userinfo) {
			initData();
		}
		et_username.setCursorVisible(false); // 设置输入框中的光标不可见
		et_username.setFocusable(false); // 无焦点
		et_username.setFocusableInTouchMode(false);
		registOne(onregister);
		// new UserOneKeyRegisterTask(onregister).execute();
	}

	private void registOne(final onRegisterBack onregister) {
		LoginUtils.registOne(acontext, new NetCallBack() {

			@Override
			public void onInitSuccess(ResultCode result) {
				onregister.toRegister();
				try {
					String password = new JSONObject(result.data)
							.getString("b");
					String username = new JSONObject(result.data)
							.getString("a");
					et_username.setText(username);
					userinfo.username = username;
					uname = username;
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onInitFail(ResultCode result) {

			}
		});
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == MResource.getIdByName(acontext, Constants.Resouce.ID,
				"bind_phone")) {
			Intent intent_view = new Intent(acontext, FloatWebActivity.class);
			intent_view.putExtra("url", Constant.URL_BAND_PHONE);
			intent_view.putExtra("title", "绑定手机");
			intent_view.putExtra("appid", YTAppService.appid);
			intent_view.putExtra("username", YTAppService.userinfo.username);
			// intent_view.putExtra("memkey", YTAppService.userinfo.token);
			intent_view.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			acontext.startActivity(intent_view);
			acontext.finish();
			return;
		}
		if (v.getId() == MResource.getIdByName(acontext, Constants.Resouce.ID,
				"btn_game_in")) {
			final String username = et_username.getText().toString().trim();
			String password = et_pwd.getText().toString().trim();

			Pattern pat = Pattern.compile("[\u4e00-\u9fa5]");
			Pattern p = Pattern.compile(".*[a-zA-Z].*[0-9]|.*[0-9].*[a-zA-Z]");
			Matcher pipeMatcher = p.matcher(username);
			// if (!pipeMatcher.matches())
			// {
			//
			// Toast.makeText(acontext, "用户必须包含英文跟数字",
			// Toast.LENGTH_SHORT).show();
			//
			// return;
			// }

			if (TextUtils.isEmpty(username)) {
				Toast.makeText(acontext, "请输入账号", Toast.LENGTH_SHORT).show();
				return;
			}
			if (TextUtils.isEmpty(password)) {
				Toast.makeText(acontext, "请输入密码", Toast.LENGTH_SHORT).show();
				return;
			}

			// if (username.length() < 6 || username.length() > 16
			// || pat.matcher(username).find()) {
			// Toast.makeText(acontext, "账号只能由6至16位英文或数字组成",
			// Toast.LENGTH_SHORT).show();
			// return;
			// }
			if (password.length() < 6 || password.length() > 16
					|| pat.matcher(password).find()) {
				Toast.makeText(acontext, "密码只能由6至16位16位英文或数字组成",
						Toast.LENGTH_SHORT).show();
				return;
			}

			if (null == userinfo) {
				initData();
			}
			userinfo.username = username;
			userinfo.password = password;
			DialogUtil.showDialog(acontext, "正在注册帐号...");
			// new RegisterAsyTask().execute();
			registNormal(acontext, username, password);

		}
	}
	/**
	 * @param bindPhoneState
	 *            处理绑定手机的状态，没有绑定手机三次就应该去提示
	 * */
	private void handleBindPhoneState() {
		getContentView().setVisibility(View.INVISIBLE);
		SelectPopupWindow menuWindow = new SelectPopupWindow(acontext, this);
		// 显示窗口
		menuWindow.showAtLocation(content_view, Gravity.CENTER
				| Gravity.CENTER_HORIZONTAL, 0, 0); // 设置layout在PopupWindow中显示的位置

	}
	/***
	 * 普通注册
	 * */
	private void registNormal(final Activity acontext, final String username,
			final String password) {
		LoginUtils.regist(acontext, username, password, new NetCallBack() {

			@Override
			public void onInitSuccess(ResultCode result) {
				String data = result.data;
				if (!TextUtils.isEmpty(data)) {
					try {
						JSONObject o = new JSONObject(data);
						int mem_id = (Integer) o.get("a");
						String user_token = (String) o.get("b");
						if (!UserLoginInfodao.getInstance(acontext)
								.findUserLoginInfoByName(username)) {
							UserLoginInfodao.getInstance(acontext)
									.saveUserLoginInfo(username, password);
						} else {
							UserLoginInfodao.getInstance(acontext)
									.deleteUserLoginByName(username);
							UserLoginInfodao.getInstance(acontext)
									.saveUserLoginInfo(username, password);
						}

						Editor editor = sp.edit();
						editor.putBoolean(Constants.ISFIRST_INSTALL, false);
						editor.commit();

						LogincallBack loginCallback = new LogincallBack();
						YTAppService.isLogin = true;
						YTAppService.userinfo = userinfo;
						YTAppService.userinfo.user_token = user_token;
						YTAppService.userinfo.mem_id = mem_id + "";
						handleBindPhoneState();
						loginCallback.mem_id = mem_id + "";
						loginCallback.user_token = GetDataImpl.PHPSESSID;
						// loginCallback.username = username;
						loginListener.loginSuccess(loginCallback);// 回调登录成功
					} catch (JSONException e) {
						e.printStackTrace();
						Util.showNetFailToast(acontext, "服务器格式不对", null);
						acontext.finish();
					}
				} else {
					Util.showNetFailToast(acontext, "服务器没有数据给我们", null);
					acontext.finish();
				}
				return;
			}

			@Override
			public void onInitFail(ResultCode result) {
				Util.showNetFailToast(acontext, "注册帐号失败", result);
			}
		});
	}

	@Override
	public View getContentView() {
		// TODO Auto-generated method stub
		return content_view;
	}

}
